// pages/details/details.js
import { getstorage } from '@/miniprogram/utils/storage'
import { getskuDetail } from '@/miniprogram/utils/API/spuAndsku'
import {addcarts} from '@/miniprogram/utils/API/car'
let globdata = getApp()
// import {userBehavior} from '@/miniprogram/behavior/behavior.js'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        token:'',
        swiperHeight: '',
        height: '',
        width: '',
        isBuyNow:true,
        spuId:0,
        topDistance: '',
        fixTop: false,
        skuBuffer: {},
        currentNavBar: 0,
        skushow: {},
        options: { id: 1, status: ['', "openByAttrIcon", "openByAddCarBtn", "openByNowChecked"], holdStatus: '' },
        deliveryList: [
            { id: 1, title: "发货", desc: "系统优先级分发", url: "/static/icons/右箭头.png" },
            { id: 2, title: "收货", desc: "客户指定", url: "/static/icons/右箭头.png" },
            { id: 3, title: "费用", desc: "根据单价免邮或最低收取", url: "/static/icons/右箭头.png" },
        ],
        descInfoList: [
            { id: 1, title: "商品详情", info: ['1'], recomented: "", actived: true },
            { id: 2, title: "规格参数", info: ["2"], recomented: "", actived: false },
            { id: 3, title: "用户评价", info: ["3"], recomented: "", actived: false }
        ],
        opsData: { skuId: '', skuName: '', num: 0, token:''},
        gloubSkuId: '',
        inputCount: 1,
        skucheckIndex: null,
        yellow: ['red', 'yellow', 'green', 'dary'],
        size: ['XX', 'M', 'S'],
        picture: ['tiger', 'pig', 'cat', 'dog'],
        sheetShow: false,
        sheetTitle: '',
        Array3D:
            [
                ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
                ['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'],
                ['XX', 'M', 'S']
            ],
        pageData: {
            keyWord: null,
            catelogId: 138,
            sort: "skuPrice_desc",
            hasStock: 1,
            // skuPrice: null,
            brandIds: '',
            attrs: '',
            pageNum: 1
        },
        skuInfo: {},
        defaultAddress: ''
    },

    //联系客服
    navToSupport(){
      // wx.navigateTo({
      //   url: '/contactUsModule/pages/index',
      // })
      wx.openCustomerServiceChat({
        corpId: 'ww5e595e92d5d8c18e',
        extInfo: {
          url: 'https://work.weixin.qq.com/kfid/kfc269a041445595345',
        },
      })


    },

    //计算sku的递归函数
    getMatrix(params) {
        let result = []
        let index = 0
        let temp = []
        let buff = []
        const descr = (arr, depth) => {
            for (let i = 0; i < arr[depth].length; i++) {
                temp[depth] = arr[depth][i]
                if (arr.length - 1 != depth) {
                    descr(arr, depth + 1)
                } else {
                    result.push(temp.join(',').split(','))
                }
            }
        }
        descr(params, 0)
        return result
    },
    //滚动条函数
    bindscroll(e) {
        let { topDistance } = this.data
        let d = parseInt(e.detail.deltaY);
        if (d < 0) {
            this.setData({
                fixTop: true
            })
        } else {
            this.setData({
                fixTop: false
            })
        }

    },
    //已废除的导航条切换
    navBindTap(e) {
        let { id } = e.currentTarget.dataset
        let that = this
        let currentNavBar = id
        that.setData({
            currentNavBar
        })
        if (this.data.fixTop) {
            wx.pageScrollTo({
                selector: '#content',
                duration: 0.3
            })
        }
    },
    //详情信息卡片切换
    swiperchange(e) {
        let id = e.detail.current
        let currentNavBar = id

        this.setData({
            currentNavBar
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let { skuId, spuId } = options
        let sendData = {}
        let {token} = this.data
        let { yellow, picture, Array3D, skuBuffer, descInfoList, currentNavBar } = this.data
        sendData.skuId = parseInt(skuId)
        sendData.spuId = parseInt(spuId)
        this.getProductionDetails(sendData)
        let res = this.getMatrix(Array3D)
        // console.log("递归函数：", res);
        this.getaddress()

        this.setData({
            gloubSkuId: skuId,
            swiperHeight: (descInfoList[currentNavBar].info.length * 600) + 'rpx',
            token,
            spuId
        })
    },
    //获取商品详情
    async getProductionDetails(data) {
        const res = await getskuDetail(data)
        let { gloubSkuId } = this.data
        let skuBuffer = res.data.data
        this.caluteSku(skuBuffer, gloubSkuId)
    },
    //切换sku
    changeSkuValue(e) {
        console.log(e);
    },
    //配货方式选择
    deliveryItemChange(e) {
        let { id } = e.currentTarget.dataset
        if (id == 1) {
            wx.navigateTo({
                url: 'url',
            })
        } else if (id == 2) {
            wx.navigateTo({
                url: '/pages/address/address',
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        wx.createSelectorQuery().select("#nav").boundingClientRect((res) => {
            if (res && res.top) {
                this.setData({
                    topDistance: parseInt(res.top)
                })
            }
        }).exec()
    },
    //添加购物车按钮
    addCarTip(e) {
        let { options,token } = this.data
        options.holdStatus = options.status[2]
        if (token == '') {
            wx.showToast({
              title: '请先登录！',
              icon:'error'
            })
            return;
        }
        this.setData({
            sheetShow: true,
            sheetTitle: "加入购物车",
            options,
        })
    },

    //添加购物车函数
    async addcartsfun(data){
      let res =  await addcarts(data)
      if (res.data.code == 200) {
          wx.showToast({
            title: '添加成功',
          })
      }
    },

    //立即购买按钮
    buyNow(e) {
        let { options,token } = this.data
        options.holdStatus = options.status[3]
        if (token == '') {
            wx.showToast({
              title: '请先登录！',
              icon:'error'
            })
            return;
        }
        this.setData({
            sheetTitle: "立即购买",
            sheetShow: true,
            options,
        })
    },

    bindplus(e) {
        this.setData({
            inputCount: this.data.inputCount + 1
        })
    },
    bindminus(e) {
        this.setData({
            inputCount: this.data.inputCount - 1
        })
    },
    SheetBindclose() {
        this.setData({
            sheetShow: false
        })
    },
    confirmBtn(e) {
        let { options,token,inputCount,opsData ,gloubSkuId,isBuyNow,spuId} = this.data
        opsData.num = inputCount
        opsData.skuId = parseInt(gloubSkuId)
        if (options.holdStatus == "openByAttrIcon") {
               wx.showToast({
                 title: '选择成功!',
               })
        } else if (options.holdStatus == "openByAddCarBtn") {
            if (token == '') {
                wx.showToast({
                  title: '请先登录！',
                  icon:'error'
                })
                return;
            }else{
                wx.showModal({
                    title:"您确认加入购物车吗？"
                }).then(()=>{
                    this.addcartsfun(opsData)
                }).catch((e)=>{
                    wx.showToast({
                      title: '您已取消',
                    })
                })
            } 
        } else if (options.holdStatus == "openByNowChecked") {
            if (token == '') {
                wx.showToast({
                  title: '请先登录！',
                  icon:'error'
                })
                return;
            }
            wx.redirectTo({
              url: `/miniprogram/pre_loadModules/orderModule/pages/orderCheck/orderCheck?isBuyNow=${isBuyNow}&count=${inputCount}&skuId=${gloubSkuId}&spuId=${spuId}`,
            })
        }
        this.setData({
            sheetShow: false
        })
    },
    //规格属性窗口打开
    openchooseAttr() {
        let { options } = this.data
        options.holdStatus = options.status[1]
        this.setData({
            sheetShow: true,
            options
        })
    },
    //sku选择矩阵按钮
    chooseSkuBtn(e) {
        let { skuid } = e.currentTarget.dataset
        let { skuInfo, gloubSkuId, skuBuffer } = this.data
        if (skuid != gloubSkuId) {
            this.caluteSku(skuBuffer, skuid),
            gloubSkuId=skuid 
        }
        console.log(gloubSkuId);
    },
    //sku计算
    caluteSku(skuBuffer, skuId) {
        let skuInfo = {}
        let { opsData, descInfoList } = this.data
        skuInfo.images = skuBuffer.images
        skuInfo.groupAttrs = skuBuffer.groupAttrs
        skuInfo.desp = skuBuffer.descript
        skuInfo.saleAttr = skuBuffer.saleAttr
        skuInfo.skuList = skuBuffer.info.map(item => {
            let obj = {}
            obj.skuSelected = false
            obj.skuId = item.skuId
            obj.skuName = item.skuSubTitle
            return obj
        })
        skuInfo.info = skuBuffer.info.filter(ite => {
            if (ite.skuId == skuId) {
                return ite
            }
        })
        let temobj = skuBuffer.desp.descript.split(',')
        let arr = []
        temobj.forEach(element => {
            let obj = {}
            obj.url = element
            arr.push(obj)
        })
        descInfoList[0].info = arr
        descInfoList[1].info = skuBuffer.groupAttrs
        opsData.currentSkuId = skuId
        opsData.currentSkuName = skuInfo.info[0].skuSubTitle
        this.setData({
            skuBuffer,
            skuInfo,
            gloubSkuId: skuId,
            opsData,
            descInfoList,

        })
    },

    getaddress() {
        let address = getstorage("address")
        let { deliveryList, defaultAddress } = this.data
        if (address != null && address != '') {
            defaultAddress = address.filter(item => {
                if (item.defaultStatus == 1) {
                    return item
                }
            })
            deliveryList[1].desc = defaultAddress[0].province + defaultAddress[0].city + defaultAddress[0].detailAddress
        }
        this.setData({
            defaultAddress,
            deliveryList
        })
    },
    onPageScroll(e) {
        console.log("父元素", e);
        let scollDistance = parseInt(e.scrollTop)
        let fixTop = scollDistance >= this.data.scollDistance
        if (this.data.fixTop != fixTop) {
            this.setData({
                fixTop
            })
        }
    },
    viewCarlist(){
        let {token } = this.data
        if (token == '') {
            wx.showToast({
              title: '请先登录',
              icon:'error'
            })
            return;
        }
         wx.switchTab({
           url: '/pages/car/car',
         })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let {token } = this.data
        token = getstorage('token')
        this.setData({
            token
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})